package com.xf.web.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import com.xf.sys.entity.SysUser;
import com.xf.sys.service.ISysUserService;
import com.xf.web.util.Constants;

/**
 *MyShiroRealm.java
 *MyShiroRealm
 *author:lb
 *date:2016年10月21日
 */
public class MyShiroRealm extends AuthorizingRealm{
	
	@Autowired
	private ISysUserService sysUserService;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
//		 String currentUsername = (String)super.getAvailablePrincipal(principals);  
//	        SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo();  
//	        //实际中可能会像上面注释的那样从数据库取得  
//	        if(null!=currentUsername && "jadyer".equals(currentUsername)){  
//	            //添加一个角色,不是配置意义上的添加,而是证明该用户拥有admin角色    
//	            simpleAuthorInfo.addRole("admin");  
//	            //添加权限  
//	            simpleAuthorInfo.addStringPermission("admin:manage");  
//	            System.out.println("已为用户[jadyer]赋予了[admin]角色和[admin:manage]权限");  
//	            return simpleAuthorInfo;  
//	        }else if(null!=currentUsername && "玄玉".equals(currentUsername)){  
//	            System.out.println("当前用户[玄玉]无授权");  
//	            return simpleAuthorInfo;  
//	        }  
		    return null; 
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		String loginUser = (String) token.getPrincipal();
		SysUser sysUser=sysUserService.selectByLoginUser(loginUser);
		if (sysUser != null)
		{
			if ("10".equals(sysUser.getStatus())) // 帐号锁定
			{
				throw new LockedAccountException();
			}
			// 从数据库查询出来的账号名和密码,与用户输入的账号和密码对比
			// 当用户执行登录时,在方法处理上要实现user.login(token);
			// 然后会自动进入这个类进行认证
			// 交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配，如果觉得人家的不好可以自定义实现
			SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
					loginUser, sysUser.getLoginPwd().toCharArray(),
					ByteSource.Util.bytes(loginUser + ""
							+ ""), getName());
			// bWVtbXNj
			// 当验证都通过后，把用户信息放在session里
			Session session = SecurityUtils.getSubject().getSession();
			session.setAttribute(Constants.USER_SESSION_KEY, sysUser);
			
			return authenticationInfo;
		} else
		{
			throw new UnknownAccountException();// 没找到帐号
		}
	}

}
